package com.share.device.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.utils.StringUtils;
import com.share.device.domain.PowerBank;
import com.share.device.mapper.PowerBankMapper;
import com.share.device.service.IPowerBankService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author HSL
 * @version 1.0
 * @data 2025/8/29 9:53
 * @desc todo
 */

@Service
public class PowerBankServiceImpl extends ServiceImpl<PowerBankMapper, PowerBank> implements IPowerBankService {

    @Resource
    private PowerBankMapper powerBankMapper;

    @Override
    public List<PowerBank> selectPowerBankList(PowerBank powerBank) {
        LambdaQueryWrapper<PowerBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(powerBank.getPowerBankNo()), PowerBank::getPowerBankNo, powerBank.getPowerBankNo());
        wrapper.like(StringUtils.isNotEmpty(powerBank.getDescription()), PowerBank::getDescription, powerBank.getDescription());
        wrapper.like(StringUtils.isNotEmpty(powerBank.getStatus()), PowerBank::getStatus, powerBank.getStatus());
        List<PowerBank> powerBankList = powerBankMapper.selectList(wrapper);
        return powerBankList;
    }


    @Override
    public int savePowerBank(PowerBank powerBank) {
        if (powerBankMapper.selectCount(new LambdaQueryWrapper<PowerBank>().eq(PowerBank::getPowerBankNo, powerBank.getPowerBankNo())) > 0) {
            throw new ServiceException("该充电宝编号已存在");
        }
        powerBankMapper.insert(powerBank);
        return 1;
    }

    @Override
    public int updatePowerBank(PowerBank powerBank) {
        PowerBank oldPowerBank = powerBankMapper.selectById(powerBank.getId());
        if (ObjectUtil.isNotEmpty(oldPowerBank) && "0".equals(oldPowerBank.getStatus())) {
            throw new ServiceException("该充电宝已进行投放，请勿修改");
        }
        if (!oldPowerBank.getPowerBankNo().equals(powerBank.getPowerBankNo())) {
            if (powerBankMapper.selectCount(new LambdaQueryWrapper<PowerBank>().eq(PowerBank::getPowerBankNo, powerBank.getPowerBankNo())) > 0) {
                throw new ServiceException("该充电宝编号已存在");
            }
        }
        powerBankMapper.updateById(powerBank);
        return 1;
    }
}
